package com.zc.demo.guava.RetaLimiterLearn;

import com.google.common.util.concurrent.RateLimiter;
import sun.tools.attach.HotSpotVirtualMachine;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhangchi9 on 2016/12/8.
 */
public class RetaLimiterLearn {
    //每秒创建五个令牌,即没200ms创建一个令牌
    RateLimiter rateLimiter = RateLimiter.create(5.0);

    public static void main(String[] args) throws Exception {
        RetaLimiterLearn rll = new RetaLimiterLearn();
        rll.oneTest();
        System.out.println("*********************");
        rll.twoTest();
        System.out.println("*********************");
        rll.threeTest();
        System.out.println("*********************");
        rll.fourTest();
    }

    public void oneTest() {
        for (int i = 0; i < 5; i++) {
            //消耗一个令牌，线程会阻塞。
            System.out.println(rateLimiter.acquire());
        }
    }

    public void twoTest() {
        //一次获取5个令牌
        System.out.println(rateLimiter.acquire(5));
        for (int i = 0; i < 5; i++) {
            System.out.println(rateLimiter.acquire());
        }
    }

    public void threeTest() throws Exception{
        //创建了一个桶容量为2且每秒新增2个令牌
        RateLimiter limiter = RateLimiter.create(2);
        //消费一个令牌，此时令牌桶可以满足（返回值为0）
        System.out.println(limiter.acquire());
        //线程暂停2秒
        Thread.sleep(2000L);
        for (int i = 0; i < 5; i++) {
            System.out.println(limiter.acquire());
        }
    }

    public void fourTest() throws InterruptedException {
        /**
         * permitsPerSecond表示每秒新增的令牌数
         * warmupPeriod表示在从冷启动速率过渡到平均速率的时间间隔。
         * unit 时间单位 毫秒
         */
        RateLimiter limiter = RateLimiter.create(5, 1000, TimeUnit.MILLISECONDS);
        for(int i = 1; i < 5;i++) {
            System.out.println(limiter.acquire());
        }
        //线程暂停1秒
        Thread.sleep(1000L);
        for(int i = 1; i < 5;i++) {
            System.out.println(limiter.acquire());
        }
    }
}

